package kau.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kau.dao.AttendInfoDAOImpl;
import kau.dao.CourseDAOImpl;
import kau.dao.CustomerDAOImpl;
import kau.dao.RegisterationDAOImpl;
import kau.dao.TagDAOImpl;
import kau.exception.RecordNotFoundException;
import kau.vo.AttendInfo;
import kau.vo.Course;
import kau.vo.Registeration;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import common.DateUtil;

public class AndroidAction extends MultiActionController {

	public ModelAndView loginCheck(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		System.out.println("android loginCheck");

		JSONObject jsonObj = null;
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(request.getParameter("android"));
		jsonObj = (JSONObject) obj;

		String custId = jsonObj.get("custId").toString();
		String password = jsonObj.get("password").toString();
		Boolean result = false;

		result = CustomerDAOImpl.getInstance().loginCheck(custId, password);
		System.out.println("ID:" + custId + "PW:" + password + "로그인결과: "
				+ result);

		request.setAttribute("result", result); // 로그인시 true , 로그인안되면 false

		nextPage.setViewName("/android/loginResult.jsp");
		return nextPage;

	}

	public ModelAndView attendCheck(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		//System.out.println("android attendCheck");

		JSONObject jsonObj = null;
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(request.getParameter("android"));
		jsonObj = (JSONObject) obj;

		String custId = jsonObj.get("custId").toString();
		String tagId = jsonObj.get("tagId").toString();
		String message;
		int checkInState;
		
		Integer courseId = null;
		//System.out.println("tdgId : "+tagId);
		try{
			 courseId = TagDAOImpl.getInstance().getCourseId(tagId);
		}catch(RecordNotFoundException e){
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkInState = 0;
			message = "사용 불가능한 TAG 입니다.";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}
		
		
		
		
		/*Integer courseId = TagDAOImpl.getInstance().getCourseId(tagId);
		
		
		if (courseId == null) {
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkInState = 0;
			message = "사용 불가능한 TAG 입니다.";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}// 없는 태그일 경우

		*/
		
		String today = DateUtil.getToday();
		System.out.println("today: "+today);
		//System.out.println("courseId : "+courseId);
	//	System.out.println("custId : "+custId);
		
		AttendInfo ai=null;
		try{
		ai= AttendInfoDAOImpl.getInstance().getAttendInfo(custId,
				courseId, today);
		
		System.out.println("ai:"+ai);
		}
		catch(RecordNotFoundException e){
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkInState = 0;
			message = "수강 기간이 아니거나 등록하지 않은 클래스입니다...";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}
		/*if (ai == null) {
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkInState = 0;
			message = "수강 기간이 아닙니다..";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}// 수강기간이 아닐경우
*/
		if (ai.getCheckInState() != 1) {
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkInState = 0;
			message = "이미 출석 등록을 하셨습니다.";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}// 이미 출석이 등록 되어 있다는 것
		



		// 정보 : 0.비정상 처리상태 1 default(결석) 2 정상 3 지각
		// int checkInState
		Course course = CourseDAOImpl.getInstance().getCourse(courseId);

		String startTime = course.getStartTime();
		String endTime = course.getEndTime();
		String nowTime = DateUtil.getNowTime();

		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
		Date dStartTime = timeFormat.parse(startTime);
		Date dEndTime = timeFormat.parse(endTime);
		Date dNowTime = timeFormat.parse(nowTime);

		long lStartTime = dStartTime.getTime();
		long lEndTime = dEndTime.getTime();
		long lNowTime = dNowTime.getTime();

		if (lNowTime <= lStartTime) {// 정상
			checkInState = 2;

			message = "정상 출석 하셨습니다.";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

		} else if (lStartTime < lNowTime && lNowTime < lEndTime) {// 지각
			checkInState = 3;

			message = "지각 하셨습니다. 다음부터 빨리 오세요";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);
		} else {// 출석 시간외 등록
			checkInState = 1;
			nextPage.setViewName("/android/attendanceResult.jsp");
			
			message = "출석 시간이 아닙니다.";

			request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);
			
			return nextPage;
		}
		
		ai.setCheckInState(checkInState);
		ai.setCheckInTime(nowTime);
		
		AttendInfoDAOImpl.getInstance().update_checkIn(ai);
		

		nextPage.setViewName("/android/attendanceResult.jsp");
		return nextPage;
	}
	
	
	public ModelAndView leavingCheck(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		//System.out.println("android attendCheck");

		JSONObject jsonObj = null;
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(request.getParameter("android"));
		jsonObj = (JSONObject) obj;

		String custId = jsonObj.get("custId").toString();
		String tagId = jsonObj.get("tagId").toString();
		String message;
		int checkOutState=1;
		
	
		//System.out.println("tdgId : "+tagId);
		Integer courseId =null;
		try{
			
			courseId = TagDAOImpl.getInstance().getCourseId(tagId);
		}catch(RecordNotFoundException e){
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkOutState = 0;
			message = "사용 불가능한 TAG 입니다.";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}
		/*
		Integer courseId = TagDAOImpl.getInstance().getCourseId(tagId);
		if (courseId == null) {
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkOutState = 0;
			message = "사용 불가능한 TAG 입니다.";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}// 없는 태그일 경우
*/
		
		
		String today = DateUtil.getToday();
		//System.out.println("today: "+today);
		//System.out.println("courseId : "+courseId);
	//	System.out.println("custId : "+custId);
		
		AttendInfo ai = null;
		
		
		try{
		ai=AttendInfoDAOImpl.getInstance().getAttendInfo(custId,
				courseId, today);
		}
		catch(RecordNotFoundException e){
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkOutState = 0;
			message = "수강 기간이 아니거나 등록하지 않은 클래스입니다...";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);
			return nextPage;

		}
		//System.out.println("ai:"+ai);
/*
		if (ai == null) {
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkOutState = 0;
			message = "수강 기간이 아닙니다..";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}// 수강기간이 아닐경우
	*/	
		if (ai.getCheckInState() == 1) {
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkOutState = 0;
			message = "출석등록을 먼처 하세요";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}// 이미 퇴실이 등록 되어 있다는 것
		
		if (ai.getCheckOutState() != 1) {
			nextPage.setViewName("/android/attendanceResult.jsp");
			checkOutState = 0;
			message = "이미 퇴실을 등록 하셨습니다.";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

			return nextPage;
		}// 이미 퇴실이 등록 되어 있다는 것
		
		
		

		// 정보 : 0.비정상 처리상태 1 default(결석) 2 정상 3 조퇴
		// int checkInState
		Course course = CourseDAOImpl.getInstance().getCourse(courseId);

		String startTime = course.getStartTime();
		String endTime = course.getEndTime();
		String nowTime = DateUtil.getNowTime();

		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
		Date dStartTime = timeFormat.parse(startTime);
		Date dEndTime = timeFormat.parse(endTime);
		Date dNowTime = timeFormat.parse(nowTime);

		long lStartTime = dStartTime.getTime();
		long lEndTime = dEndTime.getTime();
		long lNowTime = dNowTime.getTime();

		 if (lNowTime >= lEndTime) {// 정상
			checkOutState = 2;

			message = "정상 퇴실 하셨습니다.";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);

		} else if (lStartTime < lNowTime && lNowTime < lEndTime) {// 조퇴
			checkOutState = 3;

			message = "조퇴로 등록 되었습니다. ";

			//request.setAttribute("checkInState", checkInState);
			request.setAttribute("message", message);
		} 
		 
		System.out.println("checkOutState : "+checkOutState);
		 
		ai.setCheckOutState(checkOutState);
		ai.setCheckOutTime(nowTime);
		
		AttendInfoDAOImpl.getInstance().update_checkOut(ai);
		

		nextPage.setViewName("/android/attendanceResult.jsp");
		return nextPage;
	}

	public ModelAndView getCourseList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		ModelAndView nextPage = new ModelAndView();

		String custId = request.getParameter("android"); // android = custId
		JSONArray jsonArr = new JSONArray();
		
		ArrayList<Registeration> courseList = RegisterationDAOImpl.getInstance().getAllCourseId(custId);
		
		for(int i=0;i<courseList.size();i++)
		{
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("courseId", courseList.get(i).getCourseId());
			jsonObj.put("courseName", CourseDAOImpl.getInstance().getCourse(courseList.get(i).getCourseId()).getCourseName());
			jsonObj.put("lecturer", CourseDAOImpl.getInstance().getCourse(courseList.get(i).getCourseId()).getLecturer());
			jsonArr.add(jsonObj);
		}
		System.out.println(jsonArr);
		request.setAttribute("result", jsonArr);
		
		nextPage.setViewName("/android/result.jsp");
		
		return nextPage;
	}

	public ModelAndView getAttendInfo(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
	
		String custId=request.getParameter("custId");
		int courseId = Integer.parseInt(request.getParameter("courseId"));
		int courseStartTime = Integer.parseInt(DateUtil.getTimeNotsemi(CourseDAOImpl.getInstance().getCourse(courseId).getStartTime()));
		int courseEndTime = Integer.parseInt(DateUtil.getTimeNotsemi(CourseDAOImpl.getInstance().getCourse(courseId).getEndTime()));
		
		//System.out.println("courseStartTime : "+courseStartTime);
		//System.out.println("courseEndTime : "+courseEndTime);
		
		ArrayList<AttendInfo> attendInfoList = AttendInfoDAOImpl.getInstance().getAttendInfoList(custId, courseId);
		Date now = new Date();
		int currentTime = now.getHours()*100+now.getMinutes();	// 현재시간
		
		
		System.out.println(attendInfoList);
		//id,title,start,url
		JSONArray jsonArr = new JSONArray();
		
		
		for(int i=0; i<attendInfoList.size();i++){
			int checkInState = attendInfoList.get(i).getCheckInState();
			int checkOutState = attendInfoList.get(i).getCheckOutState();
			String checkInTime= attendInfoList.get(i).getCheckInTime();
			String checkOutTime= attendInfoList.get(i).getCheckOutTime();
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("id", i);
			jsonObj.put("start",attendInfoList.get(i).getDay());
			
			if(checkInState==2 && checkOutState==2){
				jsonObj.put("title", "정상\n"+checkInTime+" - "+checkOutTime);
				System.out.println("정상입니다.");
				jsonArr.add(jsonObj);
			}
			else if(checkInState==2 && checkOutState ==3)
			{
				jsonObj.put("title", "조퇴\n"+checkInTime+" - "+checkOutTime);
				System.out.println("조퇴입니다.");
				jsonArr.add(jsonObj);
			}
			else if(checkInState==3 && checkOutState ==3)
			{
				jsonObj.put("title", "지각+조퇴\n"+checkInTime+" - "+checkOutTime);
				System.out.println("지각+조퇴입니다.");
				jsonArr.add(jsonObj);
			}
			else if(checkInState==3)
			{
				jsonObj.put("title", "지각\n"+checkInTime+" - "+checkOutTime);
				System.out.println("지각입니다.");
				jsonArr.add(jsonObj);
			}
			
			else if(checkInState==1 && checkOutState ==1)
			{
				if(DateUtil.getToday().equals(attendInfoList.get(i).getDay())&& courseEndTime>currentTime){
					continue;
				}
				else{
					
				jsonObj.put("title", "결석");
				System.out.println("결석입니다.");
				jsonArr.add(jsonObj);
				}
			}
			
		}
		
		
		System.out.println("------------\n"+jsonArr.toString());
		request.setAttribute("json", jsonArr);
		nextPage.setViewName("/attendInfo/m_personalAttendInfo.jsp?json="+jsonArr);

	
		return nextPage;
	}
}
